const app = getApp();
const api = require('../../../../ws_micro_shop/utils/api.js');
const { loadingMiddleware } = require('../../../common/utils/util');
const { qyWXCheckSeesion } = require('../../../../common/utils/ws/ws-wxwork');

Page({
  data: {
    height: wx.systemInfo.windowHeight,
    page: 1,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-15.png',
      text: '暂无客户',
    },
    list: [],
    isMy: true,
    pageLoading: false,
    keyword: '',
    canPullUp: true,
    relationship: '',
    loadingText: '下拉加载',
    permissionKey: '',
    cellTabs: ['消费回访', '流失回访'],
    cellCurrentIndex: 0,
    shareInfo: {
      birthday_greeting: 0,
      comsumer_return: {
        data: [],
        new: 0,
      },
    },
    from_openid: '',
    menuList: [
      {
        name: '我的客户'
      }
    ],
    menuCurrentIndex: 0,
    isEmpty: true,
  },

  onShow() {
    // app.ws_micro_shop_globalData.role == -1 && wx.hideTabBar();
    let that = this;
    let access_token = wx.getStorageSync('access_token');
    if (access_token && app.isWXWork) {
      app.qyCheckSession({
        success: () => {
          that.init();
        },
        fail: err => {
          console.log('企业微信登录失败', err);
        },
      });
    } else {
      app.ws_micro_shoplogin().then(res => {
        that.init();
      });
    }
  },

  onPullDownRefresh() {
    wx.showLoading({
      title: '正在加载',
    });
    wx.showNavigationBarLoading();
    this.onLoad();
    setTimeout(function () {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
      wx.hideLoading();
    }, 1500);
  },

  init(){
    let that = this;
    that.setData({
      list: [],
      page: 1,
      pageLoading: false,
      permissionKey: app.ws_micro_shop_globalData.role,
      isSaas: app.ws_micro_shop_globalData.isSaas,
      from_openid: app.ws_micro_shop_globalData.openid,
      menuCurrentIndex: 0,
      cellCurrentIndex: 0,
      isMy: true,
      keyword: '',
      isEmpty: true,
    },()=>{
      // that.handleSetNavigationBarTitle();
      let { permissionKey, menuList, isSaas } = that.data;
      if (!isSaas && permissionKey == -1) {
        that.setData({
          menuCurrentIndex: 1,
          isMy: false,
        })
      }
      if (permissionKey != 1 && menuList.length == 1) {
        let item = {
          name: permissionKey == 0 ? '本店客户' : '全部客户'
        }
        menuList.push(item);
        that.setData({
          menuList
        })
      }
      
      that.getShareInfo();
      that.getList();
    })
  },

  getShareInfo() {
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.share,
      data: {
        type: 2
      },
      success: res => {
        if (res && res.code === 0 && res.data) {
          this.setData({
            shareInfo: res.data,
          });
        }
      },
      complete: res => {
        wx.hideLoading();
      },
    });
  },

  clearTxt() {
    this.setData({
      keyword: '',
      page: 1,
      list: [],
      isEmpty: true,
      pageLoading: false,
    }, () => {
      this.getList();
    });
  },

  onInput(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false,
      });
    } else {
      this.setData({
        isEmpty: true,
      });
    }
    this.setData({
      keyword: e.detail.value,
    });
  },

  onSearch(e) {
    this.setData({
      list: [],
      page: 1,
      pageLoading: false,
      keyword: this.data.keyword,
    },() => {
      this.getList();
    });
  },

  getList() {
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    const { list = [], keyword = '', isMy = '', page} = this.data;
    loadingMiddleware.before(this);
    app.ws_micro_shoprequest({
      url: api.staff.clue_index,
      data: {
        page,
        keyword,
        is_my: isMy === true ? 1 : 0,
      },
      success: res => {
        if (res && res.code === 0) {
          const newList = res.data.list;

          if (newList.length <= 0) {
            loadingMiddleware.after(res, this);
            return;
          }

          this.setData({
            list: [...list, ...newList],
          },() => {
            loadingMiddleware.after(res, this);
          });
        }
      },
      fail: res => {
        loadingMiddleware.after(res, this);
      },
      complete: res => {
        this.setData({
          pageLoading: true,
        },() => {
          wx.hideLoading();
        });
      },
    });
  },

  changeBattle(e) {
    let { isMy } = this.data;
    let { index } = e.currentTarget.dataset;
    console.info('---------changeBattle--------', e);
    this.setData(
      {
        isMy: !isMy,
        list: [],
        page: 1,
        pageLoading: false,
        menuCurrentIndex: index,
      },
      () => {
        this.getList();
        // this.handleSetNavigationBarTitle();
      },
    );
  },

  onNavigate(e) {
    const { url = '', ...params } = e.currentTarget.dataset;
    url && app.util.navigateTo(url, params);
  },

  handleSetNavigationBarTitle() {
    const { isMy = '', permissionKey = '' } = this.data;
    const title = permissionKey === 0 && !isMy ? '本店客户' : permissionKey === -1 && !isMy ? '全部客户' : '我的客户';
    const nextShow = permissionKey === 1 ? '我的客户' : (permissionKey === 0 && isMy ? '本店客户' : (permissionKey === -1 && !isMy ? '我的客户' : (permissionKey !== -1 && !isMy ? '我的客户' : '全部客户')));

    this.setData({
      relationship: nextShow,
    });

    wx.setNavigationBarTitle({
      title,
    });
  },
  onTab(e) {
    const { index = '', tabtype } = e.currentTarget.dataset;
    let obj = { [`${tabtype}CurrentIndex`]: index };
    this.setData(obj);
  },

  onMore(e) {
    wx.showActionSheet({
      itemList: ['拨打电话', '添加跟进'],
      success: res => {
        console.log(res);
        const tapIndex = res.tapIndex;
        const { mobile: phoneNumber = '', uid: customerId = '' } = e.currentTarget.dataset.item;

        switch (Number(tapIndex)) {
          case 0:
            phoneNumber &&
              wx.makePhoneCall({
                phoneNumber,
              });
              phoneNumber || wx.showToast({
                title: '该客户尚未录入联系方式',
                icon: 'none',
              })
            break;
          case 1:
            this.setData({
              // isShowMask: true,
              customerId,
            });
            let url = '/ws_micro_shop_guide/pages/record/record';
            app.util.navigateTo(url, { type: 'addFollow', id: customerId });
            break;
        }
      },
    });
  },

  onAddFollowUp() {
    const { customerId: customer_id = '', followUpText: content } = this.data;
    app.ws_micro_shoprequest({
      url: api.staff.edit_followup,
      data: {
        content,
        customer_id,
      },
      method: 'post',
      success: res => {
        if (res.code === 0) {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            mask: true,
            duration: 1500,
            success: res => {
              this.onMask();
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            mask: true,
            duration: 1500,
          });
        }
      },
    });
  },

  setFollowUpText(e) {
    this.setData({
      followUpText: e.detail.value,
    });
  },

  onMask() {
    const { isShowMask } = this.data;

    this.setData({
      isShowMask: !isShowMask,
    });
  },

  openChat(e) {

    const {
      item: { wechat_open_id = '', nickname = '', realname = '', external_userid: externalUserId = '' } = {},
    } = e.currentTarget.dataset;
    if (!app.isWXWork) {
      this.toLeaveMessage(wechat_open_id,nickname,realname);
      return;
    }

    qyWXCheckSeesion({
      success: () => {
        if (externalUserId) {
          wx.qy.openEnterpriseChat({
            externalUserIds: externalUserId,
            groupName: '',
            success: () => {
              console.log('enterprise chat opened');
            },
          });
        } else {
          this.toLeaveMessage(wechat_open_id,nickname,realname);
        }
      },
      fail: err => {
        console.log('企业微信登录失败', err);
      },
    });
  },

  toLeaveMessage(wechat_open_id = '',nickname = '',realname = '') {
    const { from_openid = '' } = this.data;
    const url = `/ws_micro_shop_guide/pages/message/detail/detail?from_openid=${from_openid}&to_openid=${wechat_open_id}&name=${nickname ||
      realname}`;
    app.util.navigateTo(url);
  },

  onReachBottom() {
    let { canPullUp, page } = this.data;
    if (canPullUp) {
      this.setData(
        {
          page: ++page,
        }, () => {
          this.getList();
        },
      );
    }
  },

  handlePartialRefresh(newList = []) {
    const { refreshId } = this.data;

    newList.map((item, index) => {
      if(item.id === refreshId) {
        this.setData({
          [`list[${index}]`]: newList[index],
        })
      }
    })
  }
});
